<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center width="50%">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="120px" size="small">
        <el-form-item label="告警类型名称" prop="alarmType">
          <el-input :disabled="disabled" placeholder="请输入告警类型名称" v-model="editForm.alarmType"></el-input>
        </el-form-item>

        <el-form-item label="获取方式" prop="alarmWay">
          <el-radio-group :disabled="disabled" v-model="editForm.alarmWay">
            <el-radio label="1">主动获取</el-radio>
            <el-radio label="2">供应商推送</el-radio>
          </el-radio-group>
        </el-form-item>

        <div v-if="editForm.alarmWay === '1'">
          <el-form-item label="设备类型" prop="eqptTypeId">
            <el-select
              placeholder="请选择设备类型"
              v-model="editForm.eqptTypeId"
              ref="eqptSelect"
              clearable
              @change="eqptTypeChange"
              :disabled="disabled"
            >
              <el-option
                v-for="item in eqptTypeList"
                :key="item.eqptTypeId"
                :label="item.eqptType"
                :value="item.eqptTypeId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="品名" prop="judgeId">
            <el-select
              v-model="editForm.judgeId"
              @change="productChange"
              clearable
              :disabled="disabled"
              ref="judgeSelect"
              placeholder="请选择品名"
              filterable
            >
              <el-option
                v-for="item in productList"
                :key="item.judgeId"
                :label="item.prductName"
                :value="item.judgeId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="监测属性" prop="eqptAttributeKey">
            <el-select
              placeholder="请选择监测属性"
              v-model="editForm.eqptAttributeKey"
              ref="attrKeySelect"
              :disabled="disabled"
            >
              <el-option
                v-for="item in eqptAttrList"
                :key="item.attrKey"
                :label="item.eqptAttribute"
                :value="item.attrKey"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- <el-form-item label="角色" prop="postRole">
          <el-select placeholder="请选择角色" v-model="editForm.postRole" @change="roleChange">
            <el-option
              v-for="item in roleList"
              :key="item.roleNo"
              :label="item.roleName"
              :value="item.roleNo"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警干系人" prop="personList">
          <el-select
            multiple
            clearable
            placeholder="请选择告警干系人"
            v-model="editForm.personList"
          >
            <el-option
              v-for="item in userList"
              :key="item.userNo"
              :label="item.userName"
              :value="item.userNo"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-row>
          <el-col :span="14">
            <el-form-item key="postRole" label="告警干系人" prop="postRole">
              <el-select placeholder="请选择角色" v-model="editForm.postRole" @change="roleChange">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleNo"
                  :label="item.roleName"
                  :value="item.roleNo"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="cus-col-margin" :span="10">
            <el-form-item key="personList" label="" prop="personList">
              <el-select multiple clearable placeholder="请选择人员" v-model="editForm.personList">
                <el-option
                  v-for="item in userList"
                  :key="item.userNo"
                  :label="item.userName"
                  :value="item.userNo"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item key="serviceId" v-if="editForm.alarmWay === '2'" label="数据服务ID" prop="serviceId">
          <el-input placeholder="请输入数据服务ID" v-model="editForm.serviceId"></el-input>
        </el-form-item>

        <el-row v-if="editForm.alarmWay === '1'">
          <el-col class="cus-col-width">
            <el-form-item class="cus-input" key="alarmFrequency" label="监测频次" prop="alarmFrequency">
              <span class="cus-tip">间隔</span>
              <el-input class="tactics-key" placeholder="请输入监测频次" v-model="editForm.alarmFrequency"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="cus-col-width cus-col-margin">
            <el-form-item key="alarmSuffix" prop="alarmSuffix">
              <el-select class="tactics-key-unit" v-model="editForm.alarmSuffix">
                <el-option
                  v-for="item in timeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <span style="margin-left: 10px">监测1次</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleOk(1)" size="small">确 定</el-button>

        <el-button v-if="!disabled" @click="handleAgain" icon="el-icon-plus" type="primary" size="small"
          >继续新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import pick from 'lodash.pick'
import { getAllRoleList, getListByRoleNo } from '../js/user'
import {
  addAlarmStrategy,
  getAlarmStrategyDetail,
  modifyAlarmStrategy,
  getProductList,
  getEqptTypeDetail
} from '../js/alarm'
import { validPositiveInteger } from '../js/validate'

export default {
  name: 'StrategyModal',
  data () {
    return {
      title: '',
      dialogVisible: false, // 编辑弹窗
      disabled: false,
      editForm: {
        alarmType: '',
        eqptTypeId: '',
        judgeId: '',
        eqptAttributeKey: '',
        postRole: '',
        personList: [],
        alarmWay: '',
        serviceId: '',
        alarmFrequency: '',
        alarmSuffix: 's'
      },
      queryParam: {
        eqptTypeId: '',
        judgeId: ''
      },
      model: {},
      rules: {
        alarmType: [{ required: true, message: '请输入告警类型名称!' }],
        eqptTypeId: [{ required: true, message: '请选择设备类型!' }],
        judgeId: [{ required: true, message: '请选择品名!' }],
        eqptAttributeKey: [{ required: true, message: '请选择监测属性!' }],
        postRole: [{ required: true, message: '请选择角色!' }],
        personList: [{ required: true, message: '请选择人员!' }],
        alarmWay: [{ required: true, message: '请选择获取方式!' }],
        serviceId: [{ required: true, message: '请输入数据服务Id!' }],
        alarmFrequency: [{ required: true, validator: validPositiveInteger, trigger: 'change' }]
      },
      roleList: [],
      userList: [],
      timeList: [
        { label: '秒', value: 's' },
        { label: '分', value: 'm' },
        { label: '时', value: 'h' }
      ],
      eqptAttrList: [],
      productList: []
    }
  },
  props: {
    eqptTypeList: {
      type: Array,
      required: true,
      default: () => []
    }
  },

  mounted () {
    this.getAllRoleList()
  },

  methods: {
    // 新增
    add () {
      this.edit({})
    },
    // 编辑
    edit (record) {
      this.dialogVisible = true
      if (record.strategyId) {
        this.title = '编辑告警类型'
        this.disabled = true
        this.getAlarmStrategyDetail(record.strategyId)
      } else {
        this.title = '添加告警类型'
      }
    },

    // 提交表单
    // type: 1:  保存  2: 继续新增
    handleOk (type) {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          let tempArr = []
          let {
            eqptTypeId,
            judgeId,
            eqptAttributeKey,
            personList,
            alarmWay,
            alarmFrequency,
            alarmSuffix,
            serviceId
          } = this.editForm
          personList.forEach(e => {
            this.userList.forEach(r => {
              if (r.userNo === e) {
                tempArr.push({
                  personId: r.userNo,
                  personName: r.userName,
                  personRole: r.roleNo,
                  personTel: r.mobile
                })
              }
            })
          })
          // 为主动获取时, 额外携带的参数
          let paramsForAlarmWay = {}
          if (alarmWay === '1') {
            let params = this.eqptAttrList.filter(e => e.attrKey === eqptAttributeKey)[0]
            paramsForAlarmWay = {
              eqptTypeName: this.$refs.eqptSelect.$data.selectedLabel,
              productName: this.$refs.judgeSelect.$data.selectedLabel,
              eqptAttribute: this.$refs.attrKeySelect.$data.selectedLabel,
              attributeSuffix: params.attrSuffix,
              attributeType: params.attrType
            }
          }
          let data = {
            ...this.editForm,
            personList: tempArr,
            eqptTypeId: alarmWay === '1' ? eqptTypeId : undefined,
            judgeId: alarmWay === '1' ? judgeId : undefined,
            eqptAttributeKey: alarmWay === '1' ? eqptAttributeKey : undefined,
            alarmFrequency: alarmWay === '1' ? alarmFrequency : undefined,
            alarmSuffix: alarmWay === '1' ? alarmSuffix : undefined,
            serviceId: alarmWay === '1' ? undefined : serviceId
          }
          const values = Object.assign({}, data, paramsForAlarmWay)
          let res, msg
          if (!this.model.strategyId) {
            res = await addAlarmStrategy(values)
            msg = '保存成功！'
          } else {
            res = await modifyAlarmStrategy(Object.assign({}, values, { strategyId: this.model.strategyId }))
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          if (type === 1) {
            this.handleCancel()
          } else {
            this.emptyData()
          }
        }
      })
    },

    // 获取告警详情
    async getAlarmStrategyDetail (strategyId) {
      const { code, data, msg } = await getAlarmStrategyDetail(strategyId)
      if (code === 0) {
        this.model = Object.assign({}, data)
        if (data.postRole) {
          this.getListByRoleNo(data.postRole, true)
        }
        if (data.eqptTypeId) {
          this.getProduct(data.eqptTypeId, true)
        }
        if (data.judgeId) {
          this.getEqptTypeDetail(data.eqptTypeId, data.judgeId, true)
        }
        this.$nextTick(() => {
          const {
            alarmType,
            eqptTypeId,
            judgeId,
            postRole,
            alarmWay,
            alarmFrequency,
            alarmSuffix,
            serviceId
          } = this.model
          this.editForm.alarmType = alarmType
          this.editForm.eqptTypeId = eqptTypeId
          this.editForm.judgeId = judgeId
          this.editForm.postRole = postRole
          this.editForm.alarmWay = alarmWay
          if (alarmWay === '1') {
            this.editForm.alarmFrequency = alarmFrequency
            this.editForm.alarmSuffix = alarmSuffix
          } else {
            this.editForm.serviceId = serviceId
          }
        })
      } else {
        this.$message.warning(msg)
      }
    },

    // 设备类型改变
    eqptTypeChange (val) {
      this.eqptAttrList = []
      this.editForm.eqptAttributeKey = ''
      this.getProduct(val)
    },

    // 品名变更 20210723 jiang
    productChange (val) {
      this.eqptAttrList = []
      this.editForm.eqptAttributeKey = ''
      this.getEqptTypeDetail(this.editForm.eqptTypeId, val)
    },

    // 获取监测属性根据设备类型  isSetAttr: 是否回显设置监测属性
    async getEqptTypeDetail (eqptTypeId, judgeId, isSetAttr) {
      this.queryParam.eqptTypeId = eqptTypeId
      this.queryParam.judgeId = judgeId
      const { code, data, msg } = await getEqptTypeDetail(this.queryParam)
      if (code === 0) {
        this.eqptAttrList = data
        if (isSetAttr) {
          this.$set(this.editForm, 'judgeId', this.model.judgeId)
          this.$set(this.editForm, 'eqptAttributeKey', this.model.eqptAttributeKey)
        }
      } else {
        this.$message.warning(msg)
      }
    },
    // 获取设备品名 20210723 jiang
    async getProduct (value, isSetAttr) {
      if (value != null && value !== '' && value !== undefined) {
        const { code, data, msg } = await getProductList(value)
        if (code === 0) {
          this.productList = data
          if (isSetAttr) {
            this.$set(this.editForm, 'eqptAttributeKey', this.model.eqptAttributeKey)
          }
        } else {
          this.$message.warning(msg)
        }
      }
    },

    // 获取角色列表
    async getAllRoleList () {
      const { code, data, msg } = await getAllRoleList()
      if (code === 0) {
        this.roleList = data
      } else {
        this.$message.warning(msg)
      }
    },
    // 角色改变
    roleChange (val) {
      this.userList = []
      this.editForm.personList = []
      this.getListByRoleNo(val)
    },
    // 根据角色获取干系人 isSetUsers: 是否回显设置干系人
    async getListByRoleNo (roleNo, isSetUsers) {
      const { code, data, msg } = await getListByRoleNo(roleNo)
      if (code === 0) {
        this.userList = data
        if (isSetUsers) {
          let personIds = this.model.personList.map(e => e.personId)
          this.$set(this.editForm, 'personList', personIds)
        }
      } else {
        this.$message.warning(msg)
      }
    },

    // 继续新增
    handleAgain () {
      this.handleOk(2)
    },

    // 取消
    handleCancel () {
      this.dialogVisible = false
      this.emptyData()
    },

    // 清空数据
    emptyData () {
      this.disabled = false
      this.model = {}
      this.userList = []
      this.$refs.editFormRef.resetFields()
      this.editForm.alarmFrequency = ''
      this.editForm.alarmSuffix = 's'
      this.editForm.serviceId = ''
      this.editForm.eqptTypeId = ''
      this.editForm.judgeId = ''
      this.editForm.eqptAttributeKey = ''
      this.editForm.personList = []
      this.editForm.postRole = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.cus-col-width {
  width: auto !important;
  .cus-tip {
    display: inline-block;
    width: 38px;
  }
  .cus-input {
    /deep/ .el-form-item__error {
      // margin-left: 38px;
    }
  }
}
.cus-col-margin {
  /deep/ .el-form-item__content {
    margin-left: 10px !important;
  }
}
.tactics-key {
  width: 180px;
}
.tactics-key-unit {
  width: 120px;
}
</style>
